#!/usr/bin/env python
# -*- coding: utf-8 -*-

from utils import log

from sqlalchemy.orm import mapper, sessionmaker
from sqlalchemy import Table, MetaData, Column, ForeignKey, Integer, BigInteger, String, Unicode, UnicodeText, DateTime, \
    UniqueConstraint
from controls.data_pool_mysql import engine

Session = sessionmaker()
Session.configure(bind=engine)

"""sight_desc_item collection has
    descid:         景点描述id（int）
    sightid:         景点id（int）
    content:         景点描述内容（str）
"""

sight_desc_table_dict = {}


class SightDescTables(object):
    def make_table(self, p_cityid):
        if sight_desc_table_dict.has_key(p_cityid):
            return sight_desc_table_dict[p_cityid]

        class SightDescItem(object):
            def __init__(self, p_cityid):
                self.p_cityid = p_cityid

            def to_dict(self):
                res = {}
                res['descid'] = self.descid
                res['sightid'] = self.sightid
                res['content'] = self.content
                return res

            def __repr__(self):
                return "%d" % (self.descid)

        metadata = MetaData()
        sight_desc_city_item_table = Table(
            'sight_desc_' + str(p_cityid), metadata,
            Column('id', Integer, primary_key=True),
            Column('sightid', Integer, nullable=False),
            Column('descid', Integer, nullable=False),
            Column('content', UnicodeText, nullable=False),
            UniqueConstraint('sightid', 'descid', name='uix_sightid_descid')
        )
        mapper(SightDescItem, sight_desc_city_item_table)
        table = {'metadata': metadata,
                 'table': sight_desc_city_item_table,
                 'class': SightDescItem}
        sight_desc_table_dict[p_cityid] = table
        return table


def create_sight_desc_item_table_if_not_exist(p_cityid):
    table = SightDescTables().make_table(p_cityid)
    table['metadata'].create_all(engine)


def add_sight_desc_item(p_cityid, p_item):
    table = SightDescTables().make_table(p_cityid)
    item = table['class'](p_cityid)
    item.descid = p_item['descid']
    item.sightid = p_item['sightid']
    item.content = p_item['content']
    try:
        session = Session()
        session.add(item)
        session.flush()
        session.commit()
        return True
    except Exception, e:
        log.exp(e)
        session.rollback()
        return False
    finally:
        session.close()


def update_sight_desc_item(p_cityid, p_item):
    if not (p_cityid and p_item):
        return False
    table = SightDescTables().make_table(p_cityid)
    try:
        updateField = {
            table['class'].content: p_item['content']
        }
        session = Session()
        session.query(table['class']).filter(
            table['class'].sightid == p_item['sightid'],
            table['class'].descid == p_item['descid']).update(updateField, synchronize_session=False)
        session.commit()
        return True
    except Exception as e:
        log.exp(e)
        session.rollback()
        return False
    finally:
        session.close()


def delete_sight_desc_item(p_cityid, p_item):
    if not (p_cityid and p_item):
        return False
    table = SightDescTables().make_table(p_cityid)
    try:
        session = Session()
        session.query(table['class']).filter(
            table['class'].sightid == p_item['sightid'],
            table['class'].descid == p_item['descid']).delete()
        session.flush()
        session.commit()
        return True
    except Exception as e:
        log.exp(e)
        session.rollback()
        return False
    finally:
        session.close()


def get_sight_desc_all(p_cityid, sight_list):
    try:
        session = Session()
        table = SightDescTables().make_table(p_cityid)
        items = session.query(table['class']).filter_by().all()
        res = {}
        sight_ids = []
        for item in items:
            if item.sightid not in res:
                res[item.sightid] = []
            res[item.sightid].append(item.to_dict())
            sight_ids.append(item.sightid)
        sight_diff = [it for it in sight_list if it not in sight_ids]
        if sight_diff:
            for sd in sight_diff:
                res[sd] = []
        return res
    except Exception as e:
        log.exp(e)
        return None
    finally:
        session.close()


def get_sight_desc_by_sightid(p_cityid, p_sightid):
    try:
        session = Session()
        table = SightDescTables().make_table(p_cityid)
        items = session.query(table['class']).filter_by(sightid=p_sightid).all()

        res = {}
        for item in items:
            if item.sightid not in res:
                res[item.sightid] = []
            res[item.sightid].append(item.to_dict())
        return res
    except Exception as e:
        log.exp(e)
        return None
    finally:
        session.close()


if __name__ == "__main__":
    test_city = 1
    create_sight_desc_item_table_if_not_exist(test_city)
    test_item = {'descid': 1,
                 'sightid': 1,
                 'content': 'test'}
    add_sight_desc_item(test_city, test_item)
    print get_sight_desc_all(test_city)
